// 全局变量
let currentPage = 1;
let isLoading = false;
let hasMorePosts = true;

// DOM 元素
const postsContainer = document.getElementById('postsContainer');
const postForm = document.getElementById('postForm');
const postContent = document.getElementById('postContent');
const charCount = document.getElementById('charCount');
const loadMoreBtn = document.getElementById('loadMore');

// API 基础 URL
const API_BASE = '/api/posts';

// 初始化
document.addEventListener('DOMContentLoaded', () => {
    loadPosts();
    setupEventListeners();
});

// 设置事件监听器
function setupEventListeners() {
    // 表单提交
    postForm.addEventListener('submit', handlePostSubmit);
    
    // 字符计数
    postContent.addEventListener('input', updateCharCount);
    
    // 无限滚动
    window.addEventListener('scroll', handleScroll);
}

// 更新字符计数
function updateCharCount() {
    const count = postContent.value.length;
    charCount.textContent = count;
    
    if (count > 450) {
        charCount.style.color = '#dc3545';
    } else {
        charCount.style.color = '#6c757d';
    }
}

// 加载帖子
async function loadPosts(page = 1, append = false) {
    if (isLoading) return;
    
    isLoading = true;
    
    try {
        const response = await fetch(`${API_BASE}?page=${page}&limit=20`);
        const posts = await response.json();
        
        if (posts.length === 0) {
            hasMorePosts = false;
            if (!append) {
                showEmptyState();
            }
            loadMoreBtn.style.display = 'none';
            return;
        }
        
        if (!append) {
            postsContainer.innerHTML = '';
        }
        
        posts.forEach(post => {
            const postElement = createPostElement(post);
            postsContainer.appendChild(postElement);
        });
        
        currentPage = page;
        
        if (posts.length < 20) {
            hasMorePosts = false;
            loadMoreBtn.style.display = 'none';
        } else {
            loadMoreBtn.style.display = 'block';
        }
        
    } catch (error) {
        console.error('加载帖子失败:', error);
        showError('加载失败，请稍后重试');
    } finally {
        isLoading = false;
    }
}

// 加载更多帖子
function loadMorePosts() {
    loadPosts(currentPage + 1, true);
}

// 处理滚动
function handleScroll() {
    if (window.innerHeight + window.scrollY >= document.body.offsetHeight - 100) {
        if (hasMorePosts && !isLoading) {
            loadMorePosts();
        }
    }
}

// 创建帖子元素
function createPostElement(post) {
    const div = document.createElement('div');
    div.className = 'post-card';
    div.dataset.postId = post.id;
    
    const time = formatTime(post.created_at);
    
    div.innerHTML = `
        <div class="post-content">${escapeHtml(post.content)}</div>
        <div class="post-meta">
            <span class="post-time">
                <i class="far fa-clock"></i> ${time}
            </span>
            <button class="like-button" onclick="likePost(${post.id})" title="点赞">
                <i class="fas fa-heart"></i>
                <span class="like-count">${post.likes}</span>
            </button>
        </div>
    `;
    
    return div;
}

// 处理发帖
async function handlePostSubmit(e) {
    e.preventDefault();
    
    const content = postContent.value.trim();
    if (!content) {
        alert('请输入内容');
        return;
    }
    
    if (content.length > 500) {
        alert('内容不能超过500字');
        return;
    }
    
    try {
        const response = await fetch(API_BASE, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ content })
        });
        
        const result = await response.json();
        
        if (response.ok) {
            // 清空输入框
            postContent.value = '';
            updateCharCount();
            
            // 添加新帖子到顶部
            const newPostElement = createPostElement(result);
            postsContainer.insertBefore(newPostElement, postsContainer.firstChild);
            
            // 滚动到顶部
            window.scrollTo({ top: 0, behavior: 'smooth' });
            
            // 显示成功提示
            showToast('发布成功！你的心声已投入树洞');
            
        } else {
            alert(result.error || '发布失败');
        }
        
    } catch (error) {
        console.error('发布失败:', error);
        alert('发布失败，请稍后重试');
    }
}

// 点赞功能
async function likePost(postId) {
    const likeButton = document.querySelector(`[data-post-id="${postId}"] .like-button`);
    const likeCount = likeButton.querySelector('.like-count');
    
    if (likeButton.classList.contains('liked')) {
        return; // 防止重复点赞
    }
    
    try {
        const response = await fetch(`${API_BASE}/${postId}/like`, {
            method: 'POST'
        });
        
        const result = await response.json();
        
        if (response.ok) {
            likeCount.textContent = result.likes;
            likeButton.classList.add('liked');
            
            // 添加动画效果
            likeButton.style.animation = 'heartBeat 0.6s ease';
            setTimeout(() => {
                likeButton.style.animation = '';
            }, 600);
            
        } else {
            alert(result.error || '点赞失败');
        }
        
    } catch (error) {
        console.error('点赞失败:', error);
        alert('点赞失败，请稍后重试');
    }
}

// 格式化时间
function formatTime(timestamp) {
    const date = new Date(timestamp);
    const now = new Date();
    const diffMs = now - date;
    
    // 如果是今天
    if (date.toDateString() === now.toDateString()) {
        const hours = date.getHours().toString().padStart(2, '0');
        const minutes = date.getMinutes().toString().padStart(2, '0');
        return `今天 ${hours}:${minutes}`;
    }
    
    // 如果是昨天
    const yesterday = new Date(now);
    yesterday.setDate(yesterday.getDate() - 1);
    if (date.toDateString() === yesterday.toDateString()) {
        const hours = date.getHours().toString().padStart(2, '0');
        const minutes = date.getMinutes().toString().padStart(2, '0');
        return `昨天 ${hours}:${minutes}`;
    }
    
    // 其他时间
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');
    const hours = date.getHours().toString().padStart(2, '0');
    const minutes = date.getMinutes().toString().padStart(2, '0');
    
    return `${month}-${day} ${hours}:${minutes}`;
}

// 转义HTML
function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

// 显示空状态
function showEmptyState() {
    postsContainer.innerHTML = `
        <div class="empty-state">
            <i class="fas fa-tree"></i>
            <h5>树洞还是空的</h5>
            <p class="text-muted">成为第一个倾诉的人吧</p>
        </div>
    `;
}

// 显示错误
function showError(message) {
    postsContainer.innerHTML = `
        <div class="empty-state">
            <i class="fas fa-exclamation-triangle text-warning"></i>
            <h5>出错了</h5>
            <p class="text-muted">${message}</p>
            <button class="btn btn-primary" onclick="loadPosts()">
                <i class="fas fa-redo"></i> 重试
            </button>
        </div>
    `;
}

// 显示提示
function showToast(message) {
    // 创建提示元素
    const toast = document.createElement('div');
    toast.className = 'position-fixed top-0 start-50 translate-middle-x mt-3';
    toast.style.zIndex = '9999';
    
    toast.innerHTML = `
        <div class="alert alert-success alert-dismissible fade show" role="alert">
            <i class="fas fa-check-circle"></i> ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    `;
    
    document.body.appendChild(toast);
    
    // 3秒后自动移除
    setTimeout(() => {
        if (toast.parentNode) {
            toast.parentNode.removeChild(toast);
        }
    }, 3000);
}
